package com.yz.jdd.voice;

import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;

import com.yz.jdd.base.utils.LogUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 文件操作类
 *
 * @author ing
 * @date 2018/3/27
 */
public final class FileUtils {
    private static final String LOGTAG = "/ing/tts";
    private static FileUtils fileUtils = new FileUtils();
    private static MessageDigest mMessageDigest = null;

    private FileUtils() {
    }

    public static FileUtils getInstance() {
        return fileUtils;
    }

    /**
     * 获取SDCARD根路径
     *
     * @return
     */
    private static StringBuffer getRootDir() throws Exception {
        return new StringBuffer().append(Environment
                .getExternalStorageDirectory());
    }

    /**
     * 获取存在SDCARD上文件的绝对路径
     *
     * @param mContext
     * @param folderName
     * @param fileName
     * @return
     * @throws Exception
     */
    public static StringBuffer getExternalFileAbsoluteDir(Context mContext,
                                                          String folderName, String fileName) throws Exception {
        StringBuffer stringBuffer = getRootDir().append(File.separator);
        stringBuffer.append(getExternalFilesDir(mContext, folderName));
        if (fileName != null) {
            if (0 == fileName.indexOf(File.separator)) {
                stringBuffer.append(fileName);
            } else {
                stringBuffer.append(File.separator);
                stringBuffer.append(fileName);
            }
        }
        return stringBuffer;
    }


    /**
     * 获取SDCARD上应用存储路径
     *
     * @param mContext
     * @param folderName
     * @return
     */
    private static StringBuffer getExternalFilesDir(Context mContext,
                                                    String folderName) throws Exception {
        String packageName = mContext.getPackageName();
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("Android").append(File.separator).append("data")
                .append(File.separator).append(packageName);
        if (folderName != null) {
            if (0 == folderName.indexOf(File.separator)) {
                stringBuffer.append(folderName);
            } else {
                stringBuffer.append(File.separator);
                stringBuffer.append(folderName);
            }
        }
        Log.d(LOGTAG, "FileUtils getExternalFilesDir "
                + stringBuffer.toString());
        return stringBuffer;
    }


    /**
     * 创建一个临时目录，用于复制临时文件，如assets目录下的离线资源文件
     *
     * @param context
     * @return
     */

    public static String createTmpDir(Context context) {
        String sampleDir = "/tts";
        String tmpDir = "/data/data/" + context.getPackageName() + sampleDir;
        if (!FileUtils.makeDir(tmpDir)) {
            tmpDir = context.getExternalFilesDir(sampleDir).getAbsolutePath();
            if (!FileUtils.makeDir(tmpDir)) {
                LogUtils.e("=== offlineResource dir created failed ");
            }
        }
        LogUtils.e("=== offlineResource dir created success: "+tmpDir);

        return tmpDir;
    }

    public static boolean makeDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            return file.mkdirs();
        } else {
            return true;
        }
    }

    /**
     * assets文件2 sdcard
     *
     * @param assets
     * @param source
     * @param dest
     * @param isCover
     * @throws IOException
     */
    public static void copyFromAssets(AssetManager assets, String source, String dest, boolean isCover) throws IOException {
        try {
            mMessageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            writeFile(assets, source, dest);
        } else if (file.exists()) {  // 若文件存在 , 对比md5
            String file1MD5 = "";
            String file2MD5 = getFileMD5String(file);
            if ("backend_female".equals(source)) {
                file1MD5 = "57c9e96801d1173186407193e26a5ecf"; // female - md5
            } else if ("frontend_model".equals(source)) {
                file1MD5 = "27ce3b75c2784353e33840c5e63b5f0c";
            }
            if (file1MD5 != null && !file1MD5.equals(file2MD5)) {
                // md5 不同重新写入
                writeFile(assets, source, dest);
            }

        }
    }

    public static void writeFile(AssetManager assets, String source, String dest) throws IOException {
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            is = assets.open(source);
            String path = dest;
            fos = new FileOutputStream(path);
            byte[] buffer = new byte[1024];
            int size = 0;
            while ((size = is.read(buffer, 0, 1024)) >= 0) {
                fos.write(buffer, 0, size);
            }
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } finally {
                    if (is != null) {
                        is.close();
                    }
                }
            }
        }
    }
    /**
     * obtain the file's MD5
     */
//    public static String getAssetsFileMD5String(AssetManager assets, String source) {
//
//        try {
//            InputStream fis = assets.open(source);
//            byte[] buffer = new byte[1024];
//            int length = -1;
//            while ((length = fis.read(buffer, 0, 1024)) > 0) {
//                mMessageDigest.update(buffer, 0, length);
//            }
//            fis.close();
//            return new BigInteger(1, mMessageDigest.digest()).toString(16);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * obtain the file's MD5
     */
    public static String getFileMD5String(File file) {
        try {
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) > 0) {
                mMessageDigest.update(buffer, 0, length);
            }
            fis.close();
            return new BigInteger(1, mMessageDigest.digest()).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
            LogUtils.e("=== getFileMD5String : " + e.toString());
        }
        return null;
    }
}
